package com.th.basemodel.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.th.basemodel.R
import com.th.basemodel.utils.ActivityManage
import com.th.basemodel.utils.StatusBarUtils


/**
 * 最底层的Activity,不带MVP和MVVM,一般不用这个
 */
abstract class AbsActivity() : AppCompatActivity(){

    /**
     * 获取Context对象
     */
    protected lateinit var mActivity: Activity
    protected lateinit var mContext: Context

    abstract fun setContentView()

    abstract fun init()

    abstract fun observeViewModel()

    /**
     * 从intent中解析数据，具体子类来实现
     */
    open protected fun getDataFromIntent(intent: Intent) {}


    override fun onCreate(savedInstanceState: Bundle?) {
        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out)

        super.onCreate(savedInstanceState)

        enableEdgeToEdge()
        setContentView()


        mActivity = this
        mContext = this.applicationContext

        //设置当前页面的顶部状态栏背景
        StatusBarUtils.immersive(this)

        //获取intent传递的数据
        if (intent != null) {
            getDataFromIntent(intent)
        }

        /** 管理Activity的栈  */
        ActivityManage.addActivity(this)

        observeViewModel()
        init()
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out)
    }



    /**
     * 只映射了onDestroy方法
     */
    override fun onDestroy() {
        super.onDestroy()

        ActivityManage.removeActivity(this)
    }

    /**
     * 设置应用的字体不随系统的字体大小而改变
     */
    override fun onConfigurationChanged(newConfig: Configuration) {
        if (newConfig.fontScale != 1f)
        //非默认值    //当接收系统的字体大小改变的时候。重置为默认
            resources
        super.onConfigurationChanged(newConfig)
    }

    override fun getResources(): Resources {
        val res = super.getResources()
        if (res.configuration.fontScale != 1f) {//非默认值
            val newConfig = Configuration()
            newConfig.setToDefaults()//设置默认
            res.updateConfiguration(newConfig, res.displayMetrics)
        }
        return res
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        ev?.let {
            if (it.action == MotionEvent.ACTION_DOWN) {
                //如果现在取得焦点的View为EditText则进入判断
                currentFocus?.let { view ->
                    if (view is EditText) {
                        if (!isInSide(view, ev) && isSoftInPutDisplayed()) {
                            hideSoftInPut(view)
                        }
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    //判断点击坐标是否在EditText内部
    private fun isInSide(currentFocus: View, ev: MotionEvent): Boolean {
        val location = intArrayOf(0, 0)
        //获取当前EditText坐标
        currentFocus.getLocationInWindow(location)
        //上下左右
        val left = location[0]
        val top = location[1]
        val right = left + currentFocus.width
        val bottom = top + currentFocus.height
        //点击坐标是否在其内部
        return (ev.x >= left && ev.x <= right && ev.y > top && ev.y < bottom)
    }

    private fun isSoftInPutDisplayed(): Boolean {
        return ViewCompat.getRootWindowInsets(window.decorView)
            ?.isVisible(WindowInsetsCompat.Type.ime()) ?: false
    }

    private fun hideSoftInPut(currentFocus: View) {
        currentFocus.let {
            //清除焦点
            it.clearFocus()
            //关闭软键盘
            val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(it.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

}
